package com.kygeng.datasearch.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.kygeng.datasearch.mapper.CompanyInfoEsRepository;
import com.kygeng.datasearch.model.DoubleData;
import com.kygeng.datasearch.util.CompanyDataUtil;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;


@RestController
@RequestMapping("/companyInfo")
public class CompanyInfoController {

    @Autowired
    private CompanyInfoEsRepository companyInfoEsRepository;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //创建搜索请求
    private SearchRequest searchRequest = new SearchRequest("company_info");

    @ResponseBody
    @PostMapping(value = "/selectByCompanyId/{companyCode}", produces = "application/json")
    public JSONObject selectByCompanyCode(@PathVariable("companyCode") String companyCode) throws IOException {

        //创建搜索对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.termsQuery("companyCode", companyCode));

        searchRequest.source(searchSourceBuilder);

        //执行搜索
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = searchResponse.getHits();

        SearchHit[] searchHits = hits.getHits();
        TotalHits totalHits = hits.getTotalHits();

        JSONObject result = new JSONObject();
        JSONArray dataList = new JSONArray();

        for (SearchHit hit : searchHits) {
            dataList.add(hit.getSourceAsMap());
        }
        result.put("data", dataList);
        result.put("total", totalHits);
        return result;
    }

    @ResponseBody
    @PostMapping(value = "/selectCompanyList")
    public JSONObject selectByCondition(@RequestBody JSONObject request) throws IOException {

        String companyNameLike = request.getString("companyName");
        String companyScale = request.getString("companyScale");
        String companyStatus = request.getString("companyStatus");
        String companyType = request.getString("companyType");

        String areaCodeList = request.getString("areaCode");//数据格式：100,200,300
        String industryCodeList = request.getString("industryCode"); //数据格式：100,200,300

        String capitalRegistered = request.getString("capitalRegistered");//数据格式：[0,1000]
        String capitalPaid = request.getString("capitalPaid");//数据格式：[1000,8000]
        String incorporationDate = request.getString("incorporationDate");//数据格式：[20240101,20240808]

        String tagList = request.getString("tags");

        //查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (!StringUtils.isEmpty(companyNameLike)) {
            boolQuery.must(QueryBuilders.matchQuery("companyName", companyNameLike));
        }
        if (!StringUtils.isEmpty(companyScale)) {
            boolQuery.must(QueryBuilders.termsQuery("companyScale", companyScale));
        }
        if (!StringUtils.isEmpty(companyStatus)) {
            boolQuery.must(QueryBuilders.termsQuery("companyStatus", companyStatus));
        }
        if (!StringUtils.isEmpty(companyType)) {
            boolQuery.must(QueryBuilders.termsQuery("companyType", companyType));
        }
        if (!StringUtils.isEmpty(areaCodeList)) {
            String[] areaCode = areaCodeList.split(",");
            boolQuery.must(QueryBuilders.termsQuery("areaCode", areaCode));
        }
        if (!StringUtils.isEmpty(industryCodeList)) {
            String[] industryCode = industryCodeList.split(",");
            boolQuery.must(QueryBuilders.termsQuery("industryCode", industryCode));
        }
        if (!StringUtils.isEmpty(capitalRegistered)) {
            DoubleData doubleData = CompanyDataUtil.getDoubleData(capitalRegistered);
            if (doubleData.getLeft() != null) {
                boolQuery.must(QueryBuilders.rangeQuery("capitalRegistered").gte(doubleData.getLeft()));
            }
            if (doubleData.getRight() != null) {
                boolQuery.must(QueryBuilders.rangeQuery("capitalRegistered").lte(doubleData.getRight()));
            }
        }
        if (!StringUtils.isEmpty(capitalPaid)) {
            DoubleData doubleData = CompanyDataUtil.getDoubleData(capitalPaid);
            if (doubleData.getLeft() != null) {
                boolQuery.must(QueryBuilders.rangeQuery("capitalPaid").gte(doubleData.getLeft()));
            }
            if (doubleData.getRight() != null) {
                boolQuery.must(QueryBuilders.rangeQuery("capitalPaid").lte(doubleData.getRight()));
            }
        }
        //TODO；优化代码逻辑 +OR的逻辑
        if (!StringUtils.isEmpty(tagList)) {
            for (String tag : tagList.split(",")) {
                boolQuery.must(QueryBuilders.matchQuery("tags", tag));
            }
        }

        //创建搜索对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(boolQuery);

        //
        searchRequest.source(searchSourceBuilder);

        //执行搜索
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = searchResponse.getHits();

        SearchHit[] searchHits = hits.getHits();
        TotalHits totalHits = hits.getTotalHits();

        JSONObject result = new JSONObject();
        JSONArray dataList = new JSONArray();

        for (SearchHit hit : searchHits) {
            dataList.add(hit.getSourceAsMap());
        }
        result.put("data", dataList);
        result.put("total", totalHits);
        return result;
    }

}
